import { EncodeRulesService } from 'src/app/@core/services/encoderRule/encode-rules.service';
import { StorehouseService } from 'src/app/@core/services/storehouse/storehouse.service';
import { SelectPositionComponent } from './../../../../@shared/components/select-position/select-position.component';
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { DValidateRules, DialogService, FormLayout,TableWidthConfig } from 'ng-devui';
import { InitialInventory, OtherWarehousingItem } from 'src/app/@core/data/inventory';
import { SelectMaterialComponent } from 'src/app/@shared/components/select-material/select-material.component';
import { SelectStorehouseComponent } from 'src/app/@shared/components/select-storehouse/select-storehouse.component';

@Component({
  selector: 'app-add-initial-inventory',
  templateUrl: './add-initial-inventory.component.html',
  styleUrls: ['./add-initial-inventory.component.scss']
})
export class AddInitialInventoryComponent {
  tableData:OtherWarehousingItem[]=[
    {
      partId: null,
      partNum: "",
      partName: "",
      partType: "",
      partUOM: "",
      description: "",
      warehouseId: null,
      warehouseName: "",
      positionId: null,
      positionName: "",
      receiptQuantity: null,
      remark: "",
    }
  ]
  InitialInventory: InitialInventory =
    {
      otherWarehousingNum: "",
      dateTime: null,
      note: "",
      createTime: null,
      createUser: "",
      otherWarehousingItems:this.tableData
  }
  msg:any;
  tableWidthConfig: TableWidthConfig[] = [
    {
      field: 'checkbox',
      width: '100px'
    },
    {
      field:'物料编码',
      width:'150px'
    },
    {
      field: '物料名称',
      width: '150px'
    },
    {
      field: '物料规格',
      width: '150px'
    },
    {
      field: '单位',
      width: '150px'
    },

    {
      field: '入库数量',
      width: '150px'
    },
    {
      field: '仓库',
      width: '150px'
    },
    {
      field: '库位',
      width: '150px'
    },
    {
      field: '备注',
      width: '150px'
    },
  ];//表格宽度配置
  dataTableOptions = {
    columns: [
      {
        field: '物料编码',
        header: '物料编码',
        fieldType: 'text',
      },
      {
        field: '物料名称',
        header: '物料名称',
        fieldType: 'text',
      },
      {
        field: '物料规格',
        header: '物料规格',
        fieldType: 'text'
      },
      {
        field: '单位',
        header: '单位',
        fieldType: 'text'
      },
      {
        field: '入库数量',
        header: '入库数量',
        fieldType: 'text'
      },
      {
        field: '仓库',
        header: '仓库',
        fieldType: 'text'
      },
      {
        field: '库位',
        header: '库位',
        fieldType: 'text'
      },
      {
        field: '备注',
        header: '备注',
        fieldType: 'text'
      },
    ]
  };//表格数据
  warehouseId: any =null;
  warehouseData: any=[];
  layoutDirection: FormLayout = FormLayout.Horizontal;
  msgs: Array<Object> = [];
  message: Array<Object> = [];
  MaterialRules:{[key:string]:DValidateRules} = {
    partNum: {
      messageShowType:'text',
      validators: [
        { required: true ,message: '*物料编码不能为空' },
        { minlength: 2, message: '*物料编码长度至少为2' },
        { maxlength: 40, message: '*物料编码长度至多为40' },
        { pattern: /^[^\s]*$/, message: '*物料编码不能包含空格' }
      ],
    }
  }
  constructor(private Router:Router,private DialogService:DialogService,private StorehouseService:StorehouseService,private EncodeRulesService:EncodeRulesService){
  }
  ngOnInit(): void {
    this.EncodeRulesService.GenerateWarehouseCodeRule('其他入库单','其他入库单').subscribe(data=>{
      this.InitialInventory.otherWarehousingNum = data
    })
    const userinfoObj = JSON.parse(localStorage.getItem('userinfo'));
    this.InitialInventory.createUser = userinfoObj.username;
    this.InitialInventory.createTime = new Date();
    this.InitialInventory.dateTime = new Date();
  }
  submit(){
    if (!this.validateSalesQuotation(this.InitialInventory)) {
      return;
    }
    this.InitialInventory.otherWarehousingItems = this.tableData
    this.StorehouseService.CreateOtherWarehousingModel(this.InitialInventory).subscribe((res:any)=>{
        this.showToast('success','成功','新增成功')
        setTimeout(() => {
          this.Router.navigate(['/pages/inventory/initial-inventory'])
        }, 1000);

    },(error:any)=>{
      this.showToast('error','失败',error.error||'服务器连接失败')
    }
  )
  }
  validateSalesQuotation(InitialInventory: InitialInventory): boolean {
    for (const [index, item] of InitialInventory.otherWarehousingItems.entries()) {
      if (!item.partNum) {
        this.showToast('warn', '错误', `第${index + 1}行物料编码不能为空`);
        return false;
      }
      if (item.receiptQuantity <= 0) {
        this.showToast('warn', '错误', `第${index + 1}行数量必须大于0`);
        return false;
      }
      if (!item.warehouseName) {
        this.showToast('warn', '错误', `第${index + 1}行仓库不能为空`);
        return false;
      }
      if (!item.positionName) {
        this.showToast('warn', '错误', `第${index + 1}行仓位不能为空`);
        return false;
      }
    }
    return true;
  }   // 所有验证通过
  cancle(){
    this.Router.navigate(['/pages/inventory/initial-inventory'])
  }
  showToast(type: any,summary:any,content:any) {
    switch (type) {
    default:
      this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  }//提示框
  add(){
    this.tableData.push({
      partId: null,
      partNum: "",
      partName: "",
      partType: "",
      partUOM: "",
      description: "",
      warehouseId: null,
      warehouseName: "",
      positionId: null,
      positionName: "",
      receiptQuantity: null,
      remark: "",
    })
  }
  remove(i: number){
    if(this.tableData.length>1){
      this.tableData.splice(i,1);
    }else if(this.tableData.length==1){
      this.tableData = [
        {
          partId: null,
          partNum: "",
          partName: "",
          partType: "",
          partUOM: "",
          description: "",
          warehouseId: null,
          warehouseName: "",
          positionId: null,
          positionName: "",
          receiptQuantity: null,
          remark: "",
        }
      ]
    }
  }// 
  selectMaterial(index:number,dialogtype?: string,){
    let data = {
      display: false,
      placeholder: '请选择物料'
    };
    const results = this.DialogService.open({
      id: 'department',
      width: '800px',
      title: '物料',
      data:data,
      content: SelectMaterialComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if(results.modalContentInstance.selectData){
              this.tableData[index].partId = results.modalContentInstance.selectData.partId
              this.tableData[index].partNum = results.modalContentInstance.selectData.partNum
              this.tableData[index].partName = results.modalContentInstance.selectData.partName
              this.tableData[index].partType = results.modalContentInstance.selectData.partType
              this.tableData[index].partUOM = results.modalContentInstance.selectData.partUOM
              this.tableData[index].warehouseId = results.modalContentInstance.selectData.warehouseID
              this.tableData[index].positionId = results.modalContentInstance.selectData.positionID
              results.modalInstance.hide();
              this.StorehouseService.getWarehouseById(this.tableData[index].warehouseId).subscribe((data:any)=>{
                this.tableData[index].warehouseName = data.warehouseName
              })
              this.StorehouseService.GetPositionById(this.tableData[index].positionId).subscribe((data:any)=>{
                this.tableData[index].positionName = data.positionName
              })
            }
            results.modalInstance.hide();
          }
        },
        {
          cssClass: 'stress',
          text: '取消',
          handler: () => {
            results.modalInstance.hide();
          }
        }
      ]
    });
  }
  selectWarehouse(index:number,dialogtype?: string){
    let data = {
      display: false,
      placeholder: '请选择仓库'
    };
    const results = this.DialogService.open({
      id: 'department',
      width: '800px',
      title: '仓库',
      data:data,
      content: SelectStorehouseComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if(results.modalContentInstance.selectData){
              this.tableData[index].warehouseId = results.modalContentInstance.selectData.warehouseId
              this.tableData[index].warehouseName = results.modalContentInstance.selectData.warehouseName
              this.tableData[index].positionId = null
              this.tableData[index].positionName = ""
              this.warehouseData = results.modalContentInstance.selectData
              results.modalInstance.hide();
            }
            results.modalInstance.hide();
          }
        },
        {
          cssClass: 'stress',
          text: '取消',
          handler: () => {
            results.modalInstance.hide();
          }
        }
      ]
    });
  }
  SelectPosition(index:number,dialogtype?: string){
    if(this.tableData[index].warehouseId==0){
      this.showToast('error','失败','请先选择仓库')
      return
    }
    let data = {
      display: false,
      warehouseData: this.warehouseData,
      warehouseId: this.tableData[index].warehouseId,
      placeholder: '请选择库位'
    };
    const results = this.DialogService.open({
      id: 'department',
      width: '800px',
      title: '库位',
      data:data,
      content: SelectPositionComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if(results.modalContentInstance.selectData){
              this.tableData[index].positionId = results.modalContentInstance.selectData.positionId
              this.tableData[index].positionName = results.modalContentInstance.selectData.positionName
              results.modalInstance.hide();
            }
            results.modalInstance.hide();
          }
        },
        {
          cssClass: 'stress',
          text: '取消',
          handler: () => {
            results.modalInstance.hide();
          }
        }
      ]
    });
  }
}
